package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;

/**
 * @author Just、倾城
 * @created 2025-10-11
 * @description
 *
 */
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 1.将请求对象和响应对象转换为HttpServletRequest, HttpServletResponse
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        
        //2.获取请求路径
        StringBuffer path = req.getRequestURL();
        log.info("拦截到的请求是：{}", path);
        //3.判断是否是登录请求
        boolean isLoginReq = ObjectUtil.equal(LOGIN_PATH, path);
        if(isLoginReq){
            chain.doFilter(request, response);
            return;
        }
        //4.不是登录请求获取请求头中名字叫做token的参数
        String token = req.getHeader(TOKEN_HEADER_NAME);
        if(ObjectUtil.isEmpty( token)){
            res.setStatus(401);
            return;
        }
        //5.验证 token
        try {
            Claims claims = JwtUtil.parseToken( token);
            // 获取用户信息 TODO 如何处理？
            log.info("-----token--------验证成功");
            String username = claims.get("username",String.class);
            log.info("---用户信息是：{}----", username);
            Integer id = claims.get("id", Integer.class);
            //将当前用户id存入当前线程池中ThreadLocal
            CurrentUserContextHolders.set(id);
            // 放行
            chain.doFilter(request, response);
            return;
        } catch (Exception e) {
            log.error("---token验证失败---");
            res.setStatus(401);
        }
    }
}
